import React, { createContext, Fragment, useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import DescriptionRow from './DescriptionRow';
import StyledDescriptions from './style';

export const percentsContext = createContext(0);

function Descriptions({ data, percents }) {
  const [rowDatas, SetRowDatas] = useState([]);

  useEffect(() => {
    const res = data.reduce((prev, item, index) => {
      const keys = Object.keys(prev);
      const row = Number(keys[keys.length - 1] || 0) + 1;
      if (
        row > 1 &&
        prev[row - 1].reduce((prev, item) => {
          return (prev += item.percent);
        }, 0) +
          item.percent <=
          percents
      ) {
        prev[row - 1].push(item);
      } else {
        prev[row] = [item];
      }
      return prev;
    }, {});
    SetRowDatas(Object.values(res));
  }, [data,percents]);
  /**
   * 将传入的数据，按行分组
   */

  // const rowDatas = Object.values(res);
  // console.log(data);
  // console.log(rowDatas);
  return (
    <StyledDescriptions>
      {rowDatas &&
        rowDatas.map((item, index) => {
          return (
            <Fragment key={index}>
              <percentsContext.Provider value={percents}>
                <DescriptionRow row={item} />
              </percentsContext.Provider>
            </Fragment>
          );
        })}
    </StyledDescriptions>
  );
}

Descriptions.propTypes = {
  data: PropTypes.array,
};

export default Descriptions;
